import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:delivery_application/common_widget/round_button.dart';
import 'package:delivery_application/common_widget/round_textfield.dart';
import 'package:delivery_application/view/home/pay.dart';
import 'package:delivery_application/view/home/person_detail.dart';
import 'package:delivery_application/view/home/myorder.dart';
import 'package:delivery_application/view/login/rest_password_view.dart';
import 'package:delivery_application/view/login/sign_up_view.dart';
import 'package:delivery_application/view/home/home_page.dart';
import 'package:delivery_application/view/home/search_view.dart';
import 'package:delivery_application/view/login/login_view.dart';
import 'package:shared_preferences/shared_preferences.dart';

class StartDeliver extends StatefulWidget {
  const StartDeliver({super.key});

  @override
  State<StartDeliver> createState() => _StartDeliverState();
}

class _StartDeliverState extends State<StartDeliver> {
  String _userName = "";
  bool _isLoggedIn = false;
  
  @override
  void initState() {
    super.initState();
    _checkLoginStatus();
  }
  
  Future<void> _checkLoginStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
    final userName = prefs.getString('userName') ?? '';
    
    setState(() {
      _isLoggedIn = isLoggedIn;
      _userName = userName;
    });
    
    if (!isLoggedIn) {
      // 如果未登录，跳转到登录页面
      Future.delayed(Duration(milliseconds: 500), () {
        if (mounted) {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const LoginView()),
          );
        }
      });
    }
  }
  
  Future<void> _logout() async {
    // 显示确认对话框
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认退出'),
        content: Text('确定要退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: Text(
              '退出',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );

    if (confirm != true) return;
    
    // 清除登录状态
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isLoggedIn', false);
    
    // 跳转到登录页面
    if (mounted) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const LoginView()),
      );
    }
  }
  
  @override
  Widget build(BuildContext context) {
    var media = MediaQuery.of(context).size; //获取当前设备的屏幕尺寸信息
    return Scaffold(
      backgroundColor: Color(0xff00AEEE),
      appBar: AppBar(
        title: Text(
          "欢迎，${_userName.isNotEmpty ? _userName : '用户'}",
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Color(0xff00AEEE),
        elevation: 0,
        automaticallyImplyLeading: false,
        actions: [
          IconButton(
            icon: Icon(Icons.exit_to_app, color: Colors.white),
            onPressed: _logout,
            tooltip: '退出登录',
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Padding(
          // Padding用于为子部件周围添加内边距（空白区域）
          padding: const EdgeInsets.symmetric(
              vertical: 20,
              horizontal:
                  25), //将会在组件的垂直方向上添加 20 逻辑像素的内边距，在水平方向上添加 25 逻辑像素的内边距，以实现在组件周围的间距效果。
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(
                height: 20,
              ),

              // Image.asset(
              //   "assets/img/personalaccount.png",
              //   width: media.width * 0.5,
              //   height: media.height * 0.2,
              //   fit: BoxFit.contain,
              // ),

              SizedBox(height: 50), // 添加("登录和Email中间的）垂直间距

              // RoundTextfield(
              //   hintText: "请输入",
              //   controller: txtordernumber,
              //   keyboardType: TextInputType.emailAddress,
              // ),
              RoundButton(
                  title: "历史订单",
                  onPressed: () {
                    //转到历史订单页面
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        //builder: (context) => const ResetPasswordView(),
                        builder: (context) => const SearchView(),
                      ),
                    );
                  }),

              SizedBox(height: 60), // 添加("登录和Email中间的）垂直间距
              // RoundTextfield(
              //   hintText: "请输入您的住址",
              //   controller: txtaddress,
              //   obscureText: true,
              // ),
              RoundButton(
                  title: "添加订单",
                  onPressed: () {
                    //转到添加订单页面
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const HomePage(),
                      ),
                    );
                  }),

              SizedBox(height: 60),
              RoundButton(
                  title: "我的信息",
                  onPressed: () {
                    //转到个人信息页面
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const DetailView(),
                      ),
                    );
                  }),

              SizedBox(height: 100),

              Image.asset(
                "assets/img/uavlogo.png",
                width: media.width * 0.5,
                height: media.height * 0.25,
                fit: BoxFit.contain,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
